package ihistoryApp.service;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
public class RankService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SimpMessagingTemplate template;

    public void updateScoreAndNotify(Long userId,String nickName,Integer newLevel) {
        Gson gson=new Gson();
        Map<String, Object> map = new HashMap<>();
        map.put("uid", userId);
        map.put("nickName", nickName);
        String rankJson=gson.toJson(map);
        // 更新 Redis
        stringRedisTemplate.opsForZSet().add("level_rank",rankJson,newLevel);
        // 通知更新
        this.template.convertAndSend("/topic/rank", getTopLevel());
    }

    public Set<ZSetOperations.TypedTuple<String>> getTopLevel() {
        return stringRedisTemplate.opsForZSet().reverseRangeWithScores("level_rank", 0, 100);
    }

}
